package isd.com.smarthome.provider;



import isd.com.smarthome.model.*;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.BaseColumns;

public class SmartHomeProvider extends ContentProvider {

	private static final String DATABASE_NAME = "SmartHomeProvider.db";
	private static final int DATABASE_VERSION = 9;
	private static final String TABLE_FLOOR = "floor";
	public static final String TABLE_GROUPSWITCH = "groupswitch";
	public static final String TABLE_ROOM = "room";
	public static final String TABLE_SWITCHES = "switches";

	public static final String AUTHORITY = "isd.com.smarthome.provider.SmartHomeProvider";
	public static final Uri FLOOR_CONTENT_URI = Uri.parse("content://"+ AUTHORITY + "/" + TABLE_FLOOR);
	public static final Uri GROUPSWITCH_CONTENT_URI = Uri.parse("content://"+ AUTHORITY + "/" + TABLE_GROUPSWITCH);
	public static final Uri ROOM_CONTENT_URI = Uri.parse("content://"+ AUTHORITY + "/" + TABLE_ROOM);
	public static final Uri SWITCHES_CONTENT_URI = Uri.parse("content://"	+ AUTHORITY + "/" + TABLE_SWITCHES);

	public interface FloorTable extends BaseColumns {
		public static final String ID_FLOOR = "IdFloor";
		public static final String NAME_FLOOR = "NameFloor";
	}

	public interface GroupSwitchTable extends BaseColumns {
		public static final String ID_GROUPSWITCH = "IdGroupSwitch";
		public static final String NAME_GROUPSWITCH = "NameGroupSwitch";
	}

	public interface RoomTable extends BaseColumns {
		public static final String ID_ROOM = "IdRoom";
		public static final String ID_FOOR = "IdFloor";
		public static final String NAME_ROOM = "NameRoom";
	}

	public interface SwitchTable extends BaseColumns {
		public static final String ID_SWITCH = "IdSwitch";
		public static final String NAME_SWITCH = "NameSwitch";
		public static final String STATUST_SWITCH = "StatusSwitch";
		public static final String ID_ROOM = "IdRoom";
		public static final String ID_GROUP = "IdGroup";
	}

	public static ContentValues getcontentValuesGroupSwitch(
			GroupSwitch groupswitch) {
		ContentValues values = new ContentValues();
		values.put(GroupSwitchTable.ID_GROUPSWITCH,
				groupswitch.getIdGroupSwitch());
		values.put(GroupSwitchTable.NAME_GROUPSWITCH,
				groupswitch.getNameGroupSwitch());
		return values;
	}

	public static ContentValues getcontentValuesRoom(Room room) {
		ContentValues values = new ContentValues();
		values.put(RoomTable.ID_ROOM, room.getIdRoom());
		values.put(RoomTable.ID_FOOR, room.getIdFloor());
		values.put(RoomTable.NAME_ROOM, room.getNameRoom());
		return values;
	}

	public static ContentValues getcontentValuesSwitch(Switches switches) {
		ContentValues values = new ContentValues();
		values.put(SwitchTable.ID_SWITCH, switches.getIdSwitch());
		values.put(SwitchTable.NAME_SWITCH, switches.getNameSwitch());
		values.put(SwitchTable.STATUST_SWITCH, switches.getStatusSwitch());
		values.put(SwitchTable.ID_ROOM, switches.getIdRoom());
		values.put(SwitchTable.ID_GROUP, switches.getIdGroup());
		return values;
	}

	public static ContentValues getcontentValuesFloor(Floor floor) {
		ContentValues values = new ContentValues();
		values.put(FloorTable.ID_FLOOR, floor.getIdFloor());
		values.put(FloorTable.NAME_FLOOR, floor.getNameFloor());
		return values;
	}

	public static void getFloor(Cursor cursor, Floor floor) {
		floor.setIdFloor(cursor.getInt(cursor.getColumnIndex(SmartHomeProvider.FloorTable.ID_FLOOR)));
		floor.setNameFloor(cursor.getString(cursor.getColumnIndex(SmartHomeProvider.FloorTable.NAME_FLOOR)));
	}

	public static void getRoom(Cursor cursor, Room room) {
		room.setIdRoom(cursor.getInt(cursor.getColumnIndex(SmartHomeProvider.RoomTable.ID_ROOM)));
		room.setIdFloor(cursor.getInt(cursor.getColumnIndex(SmartHomeProvider.RoomTable.ID_FOOR)));
		room.setNameRoom(cursor.getString(cursor.getColumnIndex(SmartHomeProvider.RoomTable.NAME_ROOM)));
	}

	public static void getGroupSwitch(Cursor cursor, GroupSwitch groupSwitch) {
		groupSwitch.setIdGroupSwitch(cursor.getInt(cursor.getColumnIndex(SmartHomeProvider.GroupSwitchTable.ID_GROUPSWITCH)));
		groupSwitch.setNameGroupSwitch(cursor.getString(cursor.getColumnIndex(SmartHomeProvider.GroupSwitchTable.NAME_GROUPSWITCH)));
	}

	public static void getSwitches(Cursor cursor, Switches switches) {
		switches.setIdSwitch(cursor.getInt(cursor.getColumnIndex(SmartHomeProvider.SwitchTable.ID_SWITCH)));
		switches.setNameSwitch(cursor.getString(cursor.getColumnIndex(SmartHomeProvider.SwitchTable.NAME_SWITCH)));
		switches.setStatusSwitch(cursor.getInt(cursor.getColumnIndex(SmartHomeProvider.SwitchTable.STATUST_SWITCH)));
		switches.setIdGroup(cursor.getInt(cursor.getColumnIndex(SmartHomeProvider.SwitchTable.ID_GROUP)));
		switches.setIdRoom(cursor.getInt(cursor.getColumnIndex(SmartHomeProvider.SwitchTable.ID_ROOM)));
		
		
	}

	public static final int FLOOR_BASE = 0;
	public static final int FLOOR = FLOOR_BASE;
	public static final int FLOOR_ID = FLOOR_BASE + 1;

	public static final int ROOM_BASE = 5;
	public static final int ROOM = ROOM_BASE;
	public static final int ROOM_ID = ROOM_BASE + 1;

	public static final int GROUPSWITCH_BASE = 10;
	public static final int GROUPSWITCH = GROUPSWITCH_BASE;
	public static final int GROUPSWITCH_ID = GROUPSWITCH_BASE + 1;

	public static final int SWITCHES_BASE = 15;
	public static final int SWITCHES = SWITCHES_BASE;
	public static final int SWITCHES_ID = SWITCHES_BASE + 1;

	public static final UriMatcher sURIMatcher = new UriMatcher(
			UriMatcher.NO_MATCH);
	static {
		final UriMatcher matcher = sURIMatcher;
		matcher.addURI(AUTHORITY, TABLE_FLOOR, FLOOR);
		matcher.addURI(AUTHORITY, TABLE_FLOOR + "/#", FLOOR_ID);

		matcher.addURI(AUTHORITY, TABLE_ROOM, ROOM);
		matcher.addURI(AUTHORITY, TABLE_ROOM + "/#", ROOM_ID);

		matcher.addURI(AUTHORITY, TABLE_GROUPSWITCH, GROUPSWITCH);
		matcher.addURI(AUTHORITY, TABLE_GROUPSWITCH + "/#", GROUPSWITCH_ID);

		matcher.addURI(AUTHORITY, TABLE_SWITCHES, SWITCHES);
		matcher.addURI(AUTHORITY, TABLE_SWITCHES + "/#", SWITCHES_ID);
	}

	private SQLiteDatabase mDatabase;

	@SuppressWarnings("deprecation")
	public synchronized SQLiteDatabase getDatabase(final Context context) {
		// Always return the cached database, if we've got one
		if (mDatabase != null) {
			return mDatabase;
		}

		final DatabaseHelper helper = new DatabaseHelper(context, DATABASE_NAME);
		mDatabase = helper.getWritableDatabase();
		if (mDatabase != null) {
			mDatabase.setLockingEnabled(true);
		}

		return mDatabase;
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context, String database_name) {
			super(context, database_name, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			String querry ="create table " + TABLE_FLOOR
					+ "("+ FloorTable._ID + " integer primary key autoincrement,"	
					+ FloorTable.ID_FLOOR + " integer,"
					+ FloorTable.NAME_FLOOR+" text not null);";					
			db.execSQL(querry);
			
			 querry= "create table " + TABLE_ROOM
				   + "("+ RoomTable._ID + " integer primary key autoincrement,"	
				   + RoomTable.ID_ROOM + " integer,"
				   + RoomTable.ID_FOOR + " integer,"
				   + RoomTable.NAME_ROOM +" text);";
				    db.execSQL(querry);
				    
			 querry= "create table " + TABLE_GROUPSWITCH
					+ "("+ GroupSwitchTable._ID + " integer primary key autoincrement,"	
					+ GroupSwitchTable.ID_GROUPSWITCH + " integer,"				    
					+ GroupSwitchTable.NAME_GROUPSWITCH +" text);";  
			 db.execSQL(querry);
			 querry= "create table " + TABLE_SWITCHES 
				 + "("+ SwitchTable._ID + " integer primary key autoincrement,"	
				 + SwitchTable.ID_SWITCH + " integer ,"
				 + SwitchTable.NAME_SWITCH+" text,"
				 + SwitchTable.STATUST_SWITCH+" integer,"
				 + SwitchTable.ID_ROOM+" integer,"
				 + SwitchTable.ID_GROUP+" integer);";
			db.execSQL(querry);	
		}
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			 
			db.execSQL("DROP TABLE IF EXISTS titles"+TABLE_FLOOR);
			db.execSQL("DROP TABLE IF EXISTS titles"+TABLE_ROOM);
			db.execSQL("DROP TABLE IF EXISTS titles"+TABLE_GROUPSWITCH);
			db.execSQL("DROP TABLE IF EXISTS titles"+TABLE_SWITCHES);
			onCreate(db);
		}
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		final int match = sURIMatcher.match(uri);
		final Context context = getContext();
		final SQLiteDatabase db = getDatabase(context);
		int result = -1;
		db.beginTransaction();
		try {
			switch(match){
				case FLOOR :
					result = db.delete(TABLE_FLOOR, selection, selectionArgs);
					db.setTransactionSuccessful();break;
				case ROOM:
		            result = db.delete(TABLE_ROOM, selection, selectionArgs);
		            db.setTransactionSuccessful();break;
				case GROUPSWITCH:
			            result = db.delete(TABLE_GROUPSWITCH, selection, selectionArgs);
			            db.setTransactionSuccessful();break;
				case SWITCHES:
		            	result = db.delete(TABLE_SWITCHES, selection, selectionArgs);
		            	db.setTransactionSuccessful();break;
		            	
			   default:
		                throw new IllegalArgumentException("Unknown URI " + uri);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
            db.endTransaction();
        }	        
        //after delete ,content provider will notified to        
        getContext().getContentResolver().notifyChange(uri, null);
		return result;
	}

	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		final int match = sURIMatcher.match(uri);
		
		final Context context = getContext();
		final SQLiteDatabase db = getDatabase(context);
		long id ;
		Uri resultUri =null;
									
			try {
				switch(match){
				case FLOOR : id = db.insert(TABLE_FLOOR,null, values);
				 resultUri = ContentUris.withAppendedId(uri,id); break;
				case ROOM:
					 id = db.insert(TABLE_ROOM, null, values);
			         resultUri = ContentUris.withAppendedId(uri, id); break;
				case GROUPSWITCH:
			         id = db.insert(TABLE_GROUPSWITCH, null, values);
			         resultUri = ContentUris.withAppendedId(uri, id); break; 
				case SWITCHES:
			         id = db.insert(TABLE_SWITCHES, null, values);
			         resultUri = ContentUris.withAppendedId(uri, id); break;     
				    
				default:
	                throw new IllegalArgumentException("Unknown URI " + uri);
				}
				
			} catch (Exception e) {
				// TODO: handle exception
			}finally {

	        }
	        getContext().getContentResolver().notifyChange(uri, null);
	        return  resultUri;
	}
	@Override
	public int bulkInsert(final Uri uri, final ContentValues[] values) {

	        final int match = sURIMatcher.match(uri);
	        final Context context = getContext();

	        // Pick the correct database for this operation
	        final SQLiteDatabase db = getDatabase(context);
	        
	        int numberInserted = 0;
	    	
	        db.beginTransaction();
	        try {
	            switch (match) {
	                case FLOOR:
	                    Floor floor = new Floor();	
	                    for ( ContentValues value : values) {
	                		String sql = "SELECT * FROM "+TABLE_FLOOR+" WHERE  "+FloorTable.ID_FLOOR + "="+value.getAsString(FloorTable.ID_FLOOR);
	                		Cursor cursor = db.rawQuery(sql, null);
	                		boolean check=false;
	                		if (cursor.moveToFirst()) {
	                			getFloor(cursor, floor);
	                		    check= true;
	                		} else {
	                		    check=false;
	                		}
	                		cursor.close();                    	
	                    	if(check==false){
	                    		db.insert(TABLE_FLOOR, null, value);
	                    	}else{

	                    		db.update(TABLE_FLOOR, value,  FloorTable.ID_FLOOR+"="+value.getAsString(FloorTable.ID_FLOOR), null);
	                    	}
	                    }

	                    db.setTransactionSuccessful();
	                    numberInserted = values.length;
	                    break; 
	                case ROOM:
	                    Room room = new Room();	
	                    for ( ContentValues value : values) {
	                		String sql = "SELECT * FROM "+TABLE_ROOM+" WHERE  "+RoomTable.ID_ROOM + "="+value.getAsString(RoomTable.ID_ROOM);
	                		Cursor cursor = db.rawQuery(sql, null);
	                		boolean check = false;
	                		if (cursor.moveToFirst()) {
	                			getRoom(cursor, room);
	                		    check= true;
	                		} else {
	                		    check=false;
	                		}
	                		cursor.close();                    	
	                    	if(check==false){
	                    		db.insert(TABLE_ROOM, null, value);
	                    	}else{

	                    		db.update(TABLE_ROOM, value,  RoomTable.ID_ROOM+"="+value.getAsString(RoomTable.ID_ROOM), null);
	                    	}
	                    }

	                    db.setTransactionSuccessful();
	                    numberInserted = values.length;
	                    break; 
	                case GROUPSWITCH:
	                    GroupSwitch group = new GroupSwitch();	
	                    for ( ContentValues value : values) {
	                		String sql = "SELECT * FROM "+TABLE_GROUPSWITCH+" WHERE  "+GroupSwitchTable.ID_GROUPSWITCH+ "="+value.getAsString(GroupSwitchTable.ID_GROUPSWITCH);
	                		Cursor cursor = db.rawQuery(sql, null);
	                		boolean check = false;
	                		if (cursor.moveToFirst()) {
	                			getGroupSwitch(cursor, group);
	                		    check= true;
	                		} else {
	                		    check=false;
	                		}
	                		cursor.close();                    	
	                    	if(check==false){
	                    		db.insert(TABLE_GROUPSWITCH, null, value);
	                    	}else{

	                    		db.update(TABLE_GROUPSWITCH, value,  GroupSwitchTable.ID_GROUPSWITCH+"="+value.getAsString(GroupSwitchTable.ID_GROUPSWITCH), null);
	                    	}
	                    }

	                    db.setTransactionSuccessful();
	                    numberInserted = values.length;
	                    break;
	                case SWITCHES:
	                    Switches switches = new Switches();	
	                    for ( ContentValues value : values) {
	                		String sql = "SELECT * FROM "+TABLE_SWITCHES+" WHERE  "+SwitchTable.ID_SWITCH + "="+value.getAsString(SwitchTable.ID_SWITCH);
	                		Cursor cursor = db.rawQuery(sql, null);
	                		boolean check = false;
	                		if (cursor.moveToFirst()) {
	                			getSwitches(cursor, switches);
	                		    check= true;
	                		} else {
	                		    check=false;
	                		}
	                		cursor.close();                    	
	                    	if(check==false){
	                    		db.insert(TABLE_SWITCHES, null, value);
	                    	}else{

	                    		db.update(TABLE_SWITCHES, value,  SwitchTable.ID_SWITCH+"="+value.getAsString(SwitchTable.ID_SWITCH), null);
	                    	}
	                    }

	                    db.setTransactionSuccessful();
	                    numberInserted = values.length;
	                    break;
	                default:
	                    throw new IllegalArgumentException("Unknown URI " + uri);
	            }
	        }catch (Exception e) {
				e.printStackTrace();
	        	
	        }finally {
	            db.endTransaction();
	            }
	        
	        context.getContentResolver().notifyChange(uri, null);
	        return numberInserted;
	    }
	
	
	@Override
	public boolean onCreate() {
		Context context = getContext();
		DatabaseHelper dbHelper = new DatabaseHelper(context,DATABASE_NAME);
		mDatabase = dbHelper.getWritableDatabase();
		return (mDatabase == null) ? false :true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,	String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();

		Cursor c = null;
		final int match = sURIMatcher.match(uri);
	  switch(match){
		case FLOOR: 
			sqlBuilder.setTables(TABLE_FLOOR);
			c = sqlBuilder.query(mDatabase, projection, selection,selectionArgs, null, null, sortOrder);
			break;
		case ROOM:
			sqlBuilder.setTables(TABLE_ROOM);
            c = sqlBuilder.query(mDatabase, projection,selection, selectionArgs, null, null, sortOrder);
            break; 
		 case GROUPSWITCH:
			 sqlBuilder.setTables(TABLE_GROUPSWITCH);
                c = sqlBuilder.query(mDatabase, projection,selection, selectionArgs, null, null, sortOrder);
                break;
		 case SWITCHES:
			 sqlBuilder.setTables(TABLE_SWITCHES);
                c = sqlBuilder.query(mDatabase, projection,selection, selectionArgs, null, null, sortOrder);
                break;        
		       
		default:
            throw new IllegalArgumentException("Unknown URI " + uri);
		}

		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection ,String[] selectionArgs) {
		// TODO Auto-generated method stub
		final int match = sURIMatcher.match(uri);
		final Context context = getContext();
		final SQLiteDatabase db = getDatabase(context);
		int result = 0;
		try {
			switch(match){
			case FLOOR: 
				result = db.update(TABLE_FLOOR, values, selection, selectionArgs); 
				break;
			case ROOM:
			    result = db.update(TABLE_ROOM, values,selection, selectionArgs);
			    break;
			case GROUPSWITCH:			  			        
			    result = db.update(TABLE_GROUPSWITCH, values,selection, selectionArgs);
			    break;
			case SWITCHES:
			     result = db.update(TABLE_SWITCHES, values,selection, selectionArgs);
			     break;    
			
			}
		} catch (Exception e)  {
			e.printStackTrace();		
		        	
        }
        
		return result;
	}

}
